package com.dyzs.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpDownloader {

	private URL url = null;	
	
	/**
	 *  private File fileDir;
	 *   fileDir = this.getFilesDir();	
	 * String mp3Url = "http://mobile.mapabc.com/download/50/abc.apk";
	
		HttpDownloader httpDownloader = new HttpDownloader();
	
		 fileDir = this.getFilesDir();
		String path = fileDir.getParent() + java.io.File.separator + fileDir.getName(); 	
		int result = httpDownloader.downFile(mp3Url, path, "abc.apk");
		
		-1:失败  0：成功 1:sd不存在
	 */

	
	public int downFile(String urlStr, String path, String fileName) {
		InputStream inputStream = null;
		try {
			FileUtils fileUtils = new FileUtils();
			inputStream = getInputStreamFromUrl(urlStr);
			File resultFile = fileUtils.write2SDFromInput(path,fileName,inputStream);
			if (resultFile == null) {
				return -1;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			try {
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	
	
	public int downFileInSd(String urlStr, String path, String fileName) {
		InputStream inputStream = null;
		try {
			SdFileUtils fileUtils = new SdFileUtils();
			if(fileUtils.checkSDCard()){
				inputStream = getInputStreamFromUrl(urlStr);
				File resultFile = fileUtils.write2SDFromInput(path,fileName,inputStream);
				if (resultFile == null) {
					return -1;
				}
			}else{
				return 1;
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			try {
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
	
	public InputStream getInputStreamFromUrl(String urlStr)
			throws MalformedURLException, IOException {
		url = new URL(urlStr);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		InputStream inputStream = urlConn.getInputStream();
		return inputStream;
	}
}